var logger=require('./logger');
var connect=require('connect');
var app=connect();

app.use(logger('method:method url:url'));
app.use('/post',restrict);
app.use('/post',admin);
app.use('/admin',restrict);
app.use('/admin',admin);
app.use(hello);
app.use(end);

app.listen(3000,function () {
    console.log('Connect port:3000',new Date());
});


function logger(req, res, next) {
    console.log(req.method,req.url);
    next();
}

function hello(req, res, next) {
    console.log('Hello.');
    next();
}

function end(req, res, next) {
    console.log('End.');
    res.end('End.');
}

function restrict(req, res, next) {
    var authorization=req.headers.authorization;
    if(!authorization)return next('Unauthor');
    //console.log('authorization:',authorization);//Basic YWRtaW50OnJvb3Q=

    var parts=authorization.split(' ');//获取以空格分隔的Base64编码，即：YWRtaW50OnJvb3Q=
    var author=new Buffer(parts[1],'base64').toString();//admint:root
    var authorArr=author.split(':');
    var user=authorArr[0];
    var pass=authorArr[1];
    //console.log('restrict>user:',user);
    //console.log('restrict>pass:',pass);

    if('admin'==user && 'root'==pass){
        next();
    }else{
        next(new Error('Error:authorization'));
    }
}

function admin(req, res, next) {
    switch(req.url){
        case '/':
            res.end('admin/root.');
            next();
            break;

        case '/users':
            res.end('admin/users');
            next();
            break;

        default:
            res.end('Not Found.');
            next();
    }
}